/**
 * 性能监控组件
 * 用于监控组件渲染次数和API请求情况
 */

import React, { useEffect, useRef } from 'react';
import { requestDebugger } from '../utils/requestDebugger';

interface PerformanceMonitorProps {
  componentName: string;
  children: React.ReactNode;
}

const PerformanceMonitor: React.FC<PerformanceMonitorProps> = ({
  componentName,
  children,
}) => {
  const renderCountRef = useRef(0);
  const mountTimeRef = useRef(Date.now());

  useEffect(() => {
    renderCountRef.current += 1;
    
    if (process.env.NODE_ENV === 'development') {
      console.log(`🔄 ${componentName} 渲染次数: ${renderCountRef.current}`);
      
      // 如果渲染次数过多，发出警告
      if (renderCountRef.current > 10) {
        console.warn(
          `⚠️ ${componentName} 渲染次数过多 (${renderCountRef.current}次)，可能存在性能问题`
        );
      }
    }
  });

  useEffect(() => {
    if (process.env.NODE_ENV === 'development') {
      console.log(`🚀 ${componentName} 组件挂载`);
      
      return () => {
        const lifeTime = Date.now() - mountTimeRef.current;
        console.log(`💀 ${componentName} 组件卸载，生命周期: ${lifeTime}ms`);
        
        // 显示请求统计
        const stats = requestDebugger.getRequestStats();
        if (stats) {
          console.log(`📊 ${componentName} 请求统计:`, stats);
        }
      };
    }
  }, [componentName]);

  return <>{children}</>;
};

export default PerformanceMonitor;
